import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Descriptions, Button, Row, Col, Spin, Modal, Image, Tag } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import { apiDetail } from '@/services/system/apimanage';
import { FileImageOutlined, FilePdfOutlined } from '@ant-design/icons';
import CustomPageContainer from '@/components/CustomPageContainer';
import { useModel } from '@umijs/max';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 1px 2px 0 rgba(0, 0, 0, 0.03)',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  buttonWrapper: {
    display: 'flex',
    justifyContent: 'center',
    marginTop: '24px',
  },
  sectionTitle: {
    fontSize: '15px',
    fontWeight: 'bold',
    margin: '16px 0 8px 0',
    borderLeft: '3px solid #1890ff',
    paddingLeft: '10px',
  },
  section: {
    marginBottom: '24px',
    padding: '16px',
    border: '1px solid #f0f0f0',
    borderRadius: '4px',
    background: '#fff',
  },
  label: {
    fontWeight: 'bold',
    textAlign: 'right',
    paddingRight: '12px',
    lineHeight: '32px',
  },
  value: {
    lineHeight: '32px',
  },
  previewButton: {
    color: token.colorPrimary,
    cursor: 'pointer',
    marginLeft: '8px',
  },
  filePreview: {
    display: 'flex',
    alignItems: 'center',
    cursor: 'pointer',
  },
  fileIcon: {
    marginRight: '8px',
    fontSize: '16px',
  },
}));

// 证件类型映射
const cardTypeMap = {
  '1': '身份证',
  '2': '港澳台身份证',
  '3': '护照',
};

const ApiManageView: React.FC = () => {
  const { styles } = useStyles();
  const location = useLocation();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [institutionData, setInstitutionData] = useState<any>({});
  const record = location.state?.record || {};
  const { institutionId } = useModel('auth');

  // 文件预览状态
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await apiDetail({
          institutionId: record.institutionId,
          institutionRoleId: record.institutionRoleId
        });

        if (response.code === 200) {
          console.log('机构详情数据:', response.data);
          setInstitutionData(response.data);
        }
      } catch (error) {
        console.error('获取详情失败:', error);
      } finally {
        setLoading(false);
      }
    };

    if (record.institutionId) {
      fetchData();
    }
  }, [record.institutionId]);

  const handleBack = () => {
    navigate('/system/apimanage');
  };

  // 打开预览
  const handlePreview = (url: string, title: string) => {
    if (!url) return;

    setPreviewImage(url);
    setPreviewOpen(true);
    setPreviewTitle(title);
  };

  // 关闭预览
  const handlePreviewCancel = () => {
    setPreviewOpen(false);
  };

  // 文件预览组件
  const FilePreviewItem = ({ url, title, type = 'image' }: { url: string, title: string, type?: string }) => {
    if (!url) return <span>未上传</span>;

    return (
      <div
        className={styles.filePreview}
        onClick={() => handlePreview(url, title)}
      >
        {type === 'pdf' || url.toLowerCase().endsWith('.pdf') ? (
          <FilePdfOutlined className={styles.fileIcon} />
        ) : (
          <FileImageOutlined className={styles.fileIcon} />
        )}
        <span>已上传</span>
        <span className={styles.previewButton}>预览</span>
      </div>
    );
  };

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.title}>机构详情</div>
          <Spin spinning={loading}>
            {/* 基本信息 */}
            <div className={styles.section}>
              <div className={styles.sectionTitle}>基本信息</div>
              <Row gutter={[24, 16]}>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>机构名称：</Col>
                    <Col span={16} className={styles.value}>{institutionData.institutionName || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>机构角色：</Col>
                    <Col span={16} className={styles.value}>{institutionData.institutionRoleId || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>账户名：</Col>
                    <Col span={16} className={styles.value}>{institutionData.accountName || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>开户行：</Col>
                    <Col span={16} className={styles.value}>{institutionData.bank || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>统一社会信用代码：</Col>
                    <Col span={16} className={styles.value}>{institutionData.creditCode || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>认证状态：</Col>
                    <Col span={16} className={styles.value}>
                      {institutionData.authenticationStatus === 1 ? (
                        <Tag color="success">已认证</Tag>
                      ) : (
                        <Tag color="error">未认证</Tag>
                      )}
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>总授信额度：</Col>
                    <Col span={16} className={styles.value}>{institutionData.allCreditLimit || '-'} 元</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>可用授信额度：</Col>
                    <Col span={16} className={styles.value}>{institutionData.creditLimit || '-'} 元</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>注册地址：</Col>
                    <Col span={16} className={styles.value}>{institutionData.address || '-'}</Col>
                  </Row>
                </Col>
              </Row>
            </div>

            {/* 法人信息 */}
            <div className={styles.section}>
              <div className={styles.sectionTitle}>法人信息</div>
              <Row gutter={[24, 16]}>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>法人代表：</Col>
                    <Col span={16} className={styles.value}>{institutionData.legalRepresentative || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>法人手机号：</Col>
                    <Col span={16} className={styles.value}>{institutionData.legalRepresentativePhone || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>法人证件类型：</Col>
                    <Col span={16} className={styles.value}>
                      {cardTypeMap[institutionData.cardType as '1' | '2' | '3'] || '-'}
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>法人证件号码：</Col>
                    <Col span={16} className={styles.value}>{institutionData.cardNumber || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>法人证件正面：</Col>
                    <Col span={16} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.cardFront || ''}
                        title="法人证件正面"
                      />
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>法人证件反面：</Col>
                    <Col span={16} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.cardBehind || ''}
                        title="法人证件反面"
                      />
                    </Col>
                  </Row>
                </Col>
              </Row>
            </div>

            {/* 管理员信息 */}
            <div className={styles.section}>
              <div className={styles.sectionTitle}>管理员信息</div>
              <Row gutter={[24, 16]}>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员：</Col>
                    <Col span={16} className={styles.value}>{institutionData.adminName || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员用户名：</Col>
                    <Col span={16} className={styles.value}>{institutionData.adminUserName || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员手机号：</Col>
                    <Col span={16} className={styles.value}>{institutionData.adminPhone || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员证件类型：</Col>
                    <Col span={16} className={styles.value}>
                      {cardTypeMap[institutionData.adminCardType as '1' | '2' | '3'] || '-'}
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员证件号码：</Col>
                    <Col span={16} className={styles.value}>{institutionData.adminCardNumber || '-'}</Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员证件正面：</Col>
                    <Col span={16} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.adminCardFront || ''}
                        title="管理员证件正面"
                      />
                    </Col>
                  </Row>
                </Col>
                <Col span={12}>
                  <Row>
                    <Col span={8} className={styles.label}>管理员证件反面：</Col>
                    <Col span={16} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.adminCardBehind || ''}
                        title="管理员证件反面"
                      />
                    </Col>
                  </Row>
                </Col>
              </Row>
            </div>

            {/* 文件信息 */}
            <div className={styles.section}>
              <div className={styles.sectionTitle}>文件信息</div>
              <Row gutter={[24, 16]}>
                <Col span={24}>
                  <Row>
                    <Col span={6} className={styles.label}>法人授权委托书：</Col>
                    <Col span={18} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.legalRepresentativePhoto || ''}
                        title="法人授权委托书"
                        type="pdf"
                      />
                    </Col>
                  </Row>
                </Col>
                <Col span={24}>
                  <Row>
                    <Col span={6} className={styles.label}>电子签名授权认证委托书：</Col>
                    <Col span={18} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.delectronicSignatureAuthentication || ''}
                        title="电子签名授权认证委托书"
                        type="pdf"
                      />
                    </Col>
                  </Row>
                </Col>
                <Col span={24}>
                  <Row>
                    <Col span={6} className={styles.label}>用户注册与服务协议：</Col>
                    <Col span={18} className={styles.value}>
                      <FilePreviewItem
                        url={institutionData.registrationServiceAgreement || ''}
                        title="用户注册与服务协议"
                        type="pdf"
                      />
                    </Col>
                  </Row>
                </Col>
              </Row>
            </div>

            <div className={styles.buttonWrapper}>
              <Button type="primary" onClick={handleBack}>
                返回
              </Button>
            </div>
          </Spin>
        </Card>
      </div>

      {/* 预览弹窗 */}
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handlePreviewCancel}
        width={800}
      >
        {previewImage.toLowerCase().endsWith('.pdf') ? (
          <iframe
            src={previewImage}
            style={{ width: '100%', height: '500px' }}
            title={previewTitle}
          />
        ) : (
          <Image
            alt={previewTitle}
            style={{ width: '100%' }}
            src={previewImage}
          />
        )}
      </Modal>
    </CustomPageContainer>
  );
};

export default ApiManageView;
